<script setup lang="ts">
defineOptions({
  name: "Addnumber"
});

import {
  delNumberByBatchCodeApi,
  insNumberApi,
  selBatchInfoApi
} from "@/api/number";
import { useUserStore } from "@/store/modules/user";
import { message } from "@/utils/message";
import { ComponentSize, dayjs, FormInstance, FormRules } from "element-plus";
import { onMounted, reactive, ref } from "vue";
import { func } from "vue-types";

interface RuleForm {
  amount: number;
  date: string;
  type: string;
  numbers: string;
  remark: string;
}

const formSize = ref<ComponentSize>("default");
const ruleFormRef = ref<FormInstance>();
const ruleForm = ref<RuleForm>({
  amount: null,
  date: dayjs().format("YYYY-MM-DD"),
  type: "福彩",
  numbers: "",
  remark: ""
});

const locationOptions = ["福彩", "体彩"];

const rules = reactive<FormRules<RuleForm>>({
  date: [
    {
      type: "date",
      required: true,
      message: "Please pick a date",
      trigger: "change"
    }
  ],
  type: [
    {
      required: true,
      message: "Please select a location",
      trigger: "change"
    }
  ]
});

const submitForm = async (formEl: FormInstance | undefined) => {
  if (!formEl) return;
  await formEl.validate((valid, fields) => {
    if (valid) {
      insNumber();
      ruleForm.value = {
        amount: null,
        date: dayjs().format("YYYY-MM-DD"),
        type: "福彩",
        numbers: "",
        remark: ""
      };
    } else {
      console.log("error submit!", fields);
    }
  });
};

const resetForm = (formEl: FormInstance | undefined) => {
  if (!formEl) return;
  formEl.resetFields();
  ruleForm.value = {
    amount: null,
    date: dayjs().format("YYYY-MM-DD"),
    type: "福彩",
    numbers: "",
    remark: ""
  };
};

interface User {
  batchCode: string;
  frequency: string;
  amount: string;
  remark: string;
  type: string;
}

// const handleEdit = (index: number, row: User) => {
//   console.log(index, row);
// };
const handleDelete = async (index: number, row: User) => {
  await delNumberByBatchCodeApi(row.batchCode);
  selBatchInfo(page.value);
  message("删除成功", { type: "success" });
};

const userId = useUserStore().userId;

// 计算号码
async function insNumber() {
  const res = await insNumberApi({
    ...ruleForm.value,
    userId
  });
  selBatchInfo(page.value);
  message(res.msg, { type: "success" });
}

// 表格数据
const tableData = ref();

const page = ref({
  page: 1,
  pageSize: 10,
  total: 0
});

// 查询批次
async function selBatchInfo(pageInfo) {
  const date = ruleForm.value.date;
  const res = await selBatchInfoApi({
    ...pageInfo,
    userId,
    date
  });
  tableData.value = res.data.records;
  page.value.total = res.data.total;
}

selBatchInfo(page.value);

// 页面变化函数
const currentChange = pageNum => {
  page.value.page = pageNum;
  selBatchInfo(page.value);
};

const pervClick = () => {
  page.value.page = page.value.page - 1;
  selBatchInfo(page.value);
};
const nextClick = () => {
  page.value.page = page.value.page + 1;
  selBatchInfo(page.value);
};

const state1 = ref("");
const handleSelect = (item: Record<string, any>) => {
  console.log(item);
};
interface RestaurantItem {
  value: string;
}

const restaurants = ref<RestaurantItem[]>([]);
const querySearch = (queryString: string, cb: any) => {
  const results = queryString
    ? restaurants.value.filter(createFilter(queryString))
    : restaurants.value;
  // call callback function to return suggestions
  cb(results);
};
const createFilter = (queryString: string) => {
  return (restaurant: RestaurantItem) => {
    return (
      restaurant.value.toLowerCase().indexOf(queryString.toLowerCase()) === 0
    );
  };
};
onMounted(() => {
  restaurants.value = loadAll();
});
const loadAll = () => {
  return [
    { value: "1" },
    { value: "2" },
    { value: "10" },
    { value: "20" },
    { value: "50" },
    { value: "100" }
  ];
};

function changeDate() {
  selBatchInfo(page.value);
}
</script>

<template>
  <div class="common-layout">
    <el-container>
      <el-header class="header">
        <el-form
          ref="ruleFormRef"
          label-position="left"
          style="max-width: 600px"
          :model="ruleForm"
          :rules="rules"
          label-width="auto"
          :size="formSize"
          :hide-required-asterisk="true"
          status-icon
        >
          <el-form-item label="金额" prop="name">
            <el-autocomplete
              v-model="ruleForm.amount"
              :fetch-suggestions="querySearch"
              clearable
              class="inline-input w-50"
              placeholder="输入金额"
              :debounce="200"
              @select="handleSelect"
            />
            <!-- <el-mention v-model="amount" :options="options" /> -->
            <!-- <el-input v-model="ruleForm .amount" /> -->
          </el-form-item>
          <el-form-item label="日期" required>
            <el-date-picker
              v-model="ruleForm.date"
              :default-value="new Date()"
              type="date"
              aria-label="请选择日期"
              placeholder="请选择日期"
              style="width: 100%"
              @change="changeDate()"
            />
          </el-form-item>
          <el-form-item label="彩票类型" prop="location">
            <el-segmented v-model="ruleForm.type" :options="locationOptions" />
          </el-form-item>
          <el-form-item label="号码" prop="desc">
            <el-input v-model="ruleForm.numbers" type="textarea" />
          </el-form-item>
          <el-form-item label="备注" prop="name">
            <el-input v-model="ruleForm.remark" />
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="submitForm(ruleFormRef)">
              计算
            </el-button>
            <el-button type="primary" @click="resetForm(ruleFormRef)"
              >重置</el-button
            >
          </el-form-item>
        </el-form>
      </el-header>
      <el-main class="main">
        <el-table :data="tableData" style="width: 100%">
          <el-table-column label="日期" prop="date" />
          <el-table-column label="类型" prop="type">
            <template #default="scope">
              <el-tag :type="scope.row.type == '福彩' ? 'primary' : 'danger'">{{
                scope.row.type
              }}</el-tag>
            </template>
          </el-table-column>
          <el-table-column label="总金额" prop="amount" />
          <el-table-column label="注数" prop="frequency" />
          <el-table-column label="备注" prop="remark" />
          <el-table-column label="操作" align="right">
            <template #default="scope">
              <!-- <el-button
                size="small"
                @click="handleEdit(scope.$index, scope.row)"
              >
                Edit
              </el-button> -->
              <el-button
                size="small"
                type="danger"
                @click="handleDelete(scope.$index, scope.row)"
              >
                删除
              </el-button>
            </template>
          </el-table-column>
        </el-table>
        <el-pagination
          background
          layout="prev, pager, next"
          :total="page.total"
          class="mt-4"
          @current-change="currentChange"
          @prev-click="pervClick"
          @next-click="nextClick"
        />
      </el-main>
    </el-container>
  </div>
</template>

<style scoped lang="scss">
.header {
  padding-left: 100px;
  padding-top: 15px;
  background-color: #fff;
  height: 30%;
  margin-bottom: 15px;
}
.main {
  background-color: #fff;
  width: 100%;
}
</style>
